<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>选课系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h1, h2 {
            color: #333;
            text-align: center;
        }
        .nav {
            margin-bottom: 20px;
        }
        .nav a {
            display: inline-block;
            padding: 5px 10px;
            background-color: #ddd;
            color: #333;
            text-decoration: none;
            border-radius: 3px;
        }
        .student-select {
            margin-bottom: 20px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background: #f9f9f9;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        th, td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        button {
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .btn-danger {
            background-color: #f44336;
        }
        .btn-danger:hover {
            background-color: #d32f2f;
        }
        .student-info {
            margin-top: 10px;
            font-weight: bold;
        }
        .tab-container {
            margin-top: 20px;
        }
        .tab-nav {
            display: flex;
            border-bottom: 1px solid #ddd;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            background: #eee;
            margin-right: 5px;
            border-radius: 5px 5px 0 0;
        }
        .tab.active {
            background: #4CAF50;
            color: white;
        }
        .tab-content {
            display: none;
            padding: 20px;
            border: 1px solid #ddd;
            border-top: none;
        }
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="nav">
            <a href="/">返回首页</a>
        </div>
        
        <h1>选课系统</h1>
        
        <div class="student-select">
            <h3>选择学生</h3>
            <select id="studentSelect">
                <option value="">-- 请选择学生 --</option>
                <!-- 学生数据将通过JavaScript动态加载 -->
            </select>
            <div id="selectedStudent" class="student-info"></div>
        </div>
        
        <div class="tab-container">
            <div class="tab-nav">
                <div class="tab active" onclick="switchTab(this, 'availableCourses')">可选课程</div>
                <div class="tab" onclick="switchTab(this, 'selectedCourses')">已选课程</div>
            </div>
            
            <div id="availableCourses" class="tab-content active">
                <h2>可选课程列表</h2>
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>课程编号</th>
                            <th>课程名称</th>
                            <th>可选名额</th>
                            <th>已选人数</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="availableCoursesTableBody">
                        <!-- 课程数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            
            <div id="selectedCourses" class="tab-content">
                <h2>已选课程列表</h2>
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>课程编号</th>
                            <th>课程名称</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="selectedCoursesTableBody">
                        <!-- 已选课程数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <script>
        let selectedStudentId = null;
        
        // 页面加载完成后获取学生列表
        document.addEventListener('DOMContentLoaded', function() {
            loadStudents();
            
            // 学生选择变化事件
            document.getElementById('studentSelect').addEventListener('change', function() {
                selectedStudentId = this.value;
                if (selectedStudentId) {
                    fetchSelectedCourses();
                    fetchAvailableCourses();
                    updateSelectedStudentInfo();
                } else {
                    document.getElementById('selectedStudent').innerText = '';
                    document.getElementById('availableCoursesTableBody').innerHTML = '';
                    document.getElementById('selectedCoursesTableBody').innerHTML = '';
                }
            });
        });
        
        // 加载学生下拉列表
        function loadStudents() {
            fetch('/api/students')
                .then(response => response.json())
                .then(data => {
                    const studentSelect = document.getElementById('studentSelect');
                    data.forEach(student => {
                        const option = document.createElement('option');
                        option.value = student.id;
                        option.textContent = `${student.studentNo} - ${student.name}`;
                        studentSelect.appendChild(option);
                    });
                })
                .catch(error => {
                    console.error('获取学生数据出错:', error);
                });
        }
        
        // 更新已选学生信息
        function updateSelectedStudentInfo() {
            const studentSelect = document.getElementById('studentSelect');
            const selectedOption = studentSelect.options[studentSelect.selectedIndex];
            if (selectedOption.value) {
                document.getElementById('selectedStudent').innerText = `当前选中: ${selectedOption.text}`;
            }
        }
        
        // 切换标签页
        function switchTab(tabElement, tabId) {
            // 移除所有标签页的活动状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 添加活动状态到当前标签页
            tabElement.classList.add('active');
            document.getElementById(tabId).classList.add('active');
        }
        
        // 获取可选课程
        function fetchAvailableCourses() {
            fetch('/api/courses')
                .then(response => response.json())
                .then(data => {
                    displayAvailableCourses(data);
                })
                .catch(error => {
                    console.error('获取可选课程出错:', error);
                });
        }
        
        // 获取已选课程
        function fetchSelectedCourses() {
            if (!selectedStudentId) return;
            
            fetch(`/api/selection/student/${selectedStudentId}`)
                .then(response => response.json())
                .then(data => {
                    displaySelectedCourses(data);
                })
                .catch(error => {
                    console.error('获取已选课程出错:', error);
                });
        }
        
        // 显示可选课程
        function displayAvailableCourses(courses) {
            const tableBody = document.getElementById('availableCoursesTableBody');
            tableBody.innerHTML = '';
            
            // 获取已选课程ID
            fetch(`/api/selection/student/${selectedStudentId}`)
                .then(response => response.json())
                .then(selectedCourses => {
                    // 获取已选课程ID集合
                    const selectedCourseIds = selectedCourses.map(course => course.id);
                    
                    courses.forEach(course => {
                        // 如果已经选了这门课，不再显示在可选列表中
                        if (selectedCourseIds.includes(course.id)) {
                            return;
                        }
                        
                        const row = document.createElement('tr');
                        const availableSlots = course.maxCapacity - course.currentEnrollment;
                        
                        row.innerHTML = `
                            <td>${course.id || ''}</td>
                            <td>${course.courseCode || ''}</td>
                            <td>${course.courseName || ''}</td>
                            <td>${availableSlots}</td>
                            <td>${course.currentEnrollment || 0}/${course.maxCapacity || 0}</td>
                            <td>
                                <button 
                                    ${availableSlots <= 0 ? 'disabled' : ''} 
                                    onclick="enrollCourse(${course.id})"
                                    ${availableSlots <= 0 ? 'style="background-color: #cccccc;"' : ''}
                                >
                                    ${availableSlots <= 0 ? '已满' : '选课'}
                                </button>
                            </td>
                        `;
                        
                        tableBody.appendChild(row);
                    });
                })
                .catch(error => {
                    console.error('检查已选课程出错:', error);
                });
        }
        
        // 显示已选课程
        function displaySelectedCourses(courses) {
            const tableBody = document.getElementById('selectedCoursesTableBody');
            tableBody.innerHTML = '';
            
            courses.forEach(course => {
                const row = document.createElement('tr');
                
                row.innerHTML = `
                    <td>${course.id || ''}</td>
                    <td>${course.courseCode || ''}</td>
                    <td>${course.courseName || ''}</td>
                    <td>
                        <button class="btn-danger" onclick="dropCourse(${course.id})">退课</button>
                    </td>
                `;
                
                tableBody.appendChild(row);
            });
        }
        
        // 选课
        function enrollCourse(courseId) {
            if (!selectedStudentId) {
                alert('请先选择学生');
                return;
            }
            
            fetch('/api/selection/enroll', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `studentId=${selectedStudentId}&courseId=${courseId}`
            })
            .then(response => response.json())
            .then(success => {
                if (success) {
                    alert('选课成功');
                    fetchSelectedCourses();
                    fetchAvailableCourses();
                } else {
                    alert('选课失败，课程可能已满或已选过此课程');
                }
            })
            .catch(error => {
                console.error('选课出错:', error);
                alert('选课出错');
            });
        }
        
        // 退课
        function dropCourse(courseId) {
            if (!selectedStudentId) {
                alert('请先选择学生');
                return;
            }
            
            if (confirm('确定要退选此课程吗？')) {
                fetch('/api/selection/drop', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `studentId=${selectedStudentId}&courseId=${courseId}`
                })
                .then(response => response.json())
                .then(success => {
                    if (success) {
                        alert('退课成功');
                        fetchSelectedCourses();
                        fetchAvailableCourses();
                    } else {
                        alert('退课失败');
                    }
                })
                .catch(error => {
                    console.error('退课出错:', error);
                    alert('退课出错');
                });
            }
        }
    </script>
</body>
</html> 